package com.yksj.healthtalk.ui.doctorstation.service;

import org.universalimageloader.core.ImageLoader;

import sfs2x.client.core.SFSEvent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LevelListDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.LodingFragmentDialog;
import com.yksj.healthtalk.entity.CustomerInfoEntity;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonsfHttpResponseHandler;
import com.yksj.healthtalk.net.http.RequestParams;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.services.MessagePushService;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.app.AppData;
import com.yksj.healthtalk.ui.app.HTalkApplication;
import com.yksj.healthtalk.utils.FriendHttpUtil;
import com.yksj.healthtalk.utils.PersonInfoUtil;
import com.yksj.healthtalk.utils.ToastUtil;


/**
 * 关注我的患者
 * @author zhao
 */
public class DoctorAttentionMyListActivity extends BaseFragmentActivity implements OnClickListener, OnItemClickListener {
	
	ListView mListView;
	DataListAdapter mAdapter;
	
	private IntentFilter filter;
	
	BroadcastReceiver receiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equals(MessagePushService.ACTION_COLLECT_FRIEND)) {
			LodingFragmentDialog.dismiss(getSupportFragmentManager());
				String result = intent.getStringExtra("result");
				if (result.equals("0")) {
					ToastUtil.showShort(DoctorAttentionMyListActivity.this, R.string.groupNewFail);
				} else if (result.equals("-1")) {
					ToastUtil.showShort(DoctorAttentionMyListActivity.this,R.string.against__blacklist_operations);
				} else {
					onQueryData();
				}
				
			}
		}
	};
	
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.doctor_attention_my_list_layout);
		initUI();
		onQueryData();
	}
	
	@Override
	public void onStop() {
		unregisterReceiver(receiver);
		super.onStop();
	}

	@Override
	public void onStart() {
		filter = new IntentFilter();
		filter.addAction(MessagePushService.ACTION_COLLECT_FRIEND);
		filter.addAction(SFSEvent.CONNECTION_LOST);
		filter.addAction(MessagePushService.ACTION_MESSAGE);
		registerReceiver(receiver, filter);
		super.onStart();
	}
	
	private void initUI(){
		initTitle();
		titleTextV.setText("关注我的患者");
		titleLeftBtn.setOnClickListener(this);
		mListView = (ListView)findViewById(R.id.listView1);
		mListView.setOnItemClickListener(this);
		mListView.setAdapter(mAdapter = new DataListAdapter());
	}
	
	private void onQueryData(){
		RequestParams params = new RequestParams();
		params.put("customerId",SmartFoxClient.getLoginUserId());
		params.put("type","6");
		params.put("pageSize","1");
		params.put("pageNum",String.valueOf(Integer.MAX_VALUE));
		HttpRestClient.doHttpFindmypatientdetails32(params, new JsonsfHttpResponseHandler(this){
			@Override
			public void onSuccess(int statusCode, JSONArray response) {
				super.onSuccess(statusCode, response);
				mAdapter.onDataChange(response);
			}
		});
	}

	@Override
	public void onClick(View v) {
		switch(v.getId()){
		case R.id.title_back://
			setResult(RESULT_OK, getIntent());
			finish();
			overridePendingTransition(R.anim.back_enter, R.anim.back_exit);
			break;
		}
	}
	
	class DataListAdapter extends BaseAdapter{
		JSONArray mArray  = new JSONArray();
		private ImageLoader imageLoader;
		private Drawable attenDrawable;
		private Drawable notAttenDrawable;
		private AppData appData;
		public DataListAdapter() {
			imageLoader = ImageLoader.getInstance();
			attenDrawable = getApplicationContext().getResources().getDrawable(R.drawable.attention);
			notAttenDrawable = getApplicationContext().getResources().getDrawable(R.drawable.not_attention);
			appData=HTalkApplication.getAppData();
		}
		
		private void onDataChange(JSONArray array){
			this.mArray = array;
			notifyDataSetChanged();
		}
		
		@Override
		public int getCount() {
			return mArray.size();
		}

		@Override
		public JSONObject getItem(int arg0) {
			return mArray.getJSONObject(arg0);
		}

		@Override
		public long getItemId(int arg0) {
			return arg0;
		}

		@Override
		public View getView(int arg0, View convertView, ViewGroup arg2) {
			final viewHolder holder;
			final JSONObject jsonObject = getItem(arg0);
			if (convertView == null) {
				holder = new viewHolder();
				convertView = getLayoutInflater().inflate(R.layout.friendlist_iterm,null) ;
				holder.distance = (TextView)convertView.findViewById(R.id.distance);
				holder.head = (ImageView) convertView.findViewById(R.id.head_image);
				holder.personName = (TextView) convertView.findViewById(R.id.name);
				holder.headSex = (ImageView) convertView.findViewById(R.id.head_sex);
				holder.v = (ImageView) convertView.findViewById(R.id.v);
				holder.note = (TextView) convertView.findViewById(R.id.note);
				holder.attentionSalon = (ImageView)convertView.findViewById(R.id.is_friend);
				holder.message = (TextView) convertView.findViewById(R.id.item_dele);
				convertView.setTag(holder);
				holder.headSex.setImageDrawable(getResources().getDrawable(R.drawable.sex_drawable));
			}else {
				holder = (viewHolder) convertView.getTag();
			}
			
			if(!jsonObject.containsKey("display_name")){
				if(jsonObject.getString("customerNickname").length() != 0){
					String name = jsonObject.getString("customerNickname")+"("+jsonObject.getString("customerAccounts")+")";
					jsonObject.put("display_name", name);
				}else{
					jsonObject.put("display_name", jsonObject.getString("customerAccounts"));
				}
			}
			holder.note.setText(jsonObject.getString("personalNarrate"));
			holder.personName.setText(jsonObject.getString("display_name"));
			final LevelListDrawable listDrawable = (LevelListDrawable)holder.headSex.getDrawable();
			listDrawable.setLevel(jsonObject.getIntValue("customerSex"));
			holder.headSex.getDrawable();
			holder.v.setVisibility(CustomerInfoEntity.isShowDoctorV(jsonObject.getIntValue("roleId"))?View.VISIBLE:View.GONE);
			imageLoader.displayImage(jsonObject.getString("customerSex"),
					jsonObject.getString("clientIconBackground"),
					holder.head);
			holder.head.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					PersonInfoUtil.choiceActivity(jsonObject.getString("customerId"), DoctorAttentionMyListActivity.this, jsonObject.getString("roleId"));
				}
			});
			final CustomerInfoEntity entity=new CustomerInfoEntity();
			entity.setIsAttentionFriend(jsonObject.getIntValue("relationType"));
			if (entity.getIsAttentionFriend() !=0 && entity.getIsAttentionFriend() !=2) {
				holder.attentionSalon.setImageDrawable(notAttenDrawable);
			}else {
				holder.attentionSalon.setImageDrawable(attenDrawable);
			}
			
			holder.attentionSalon.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					entity.setId(jsonObject.getString("customerId"));
					if("".equals(jsonObject.getString("remarksName"))){
						entity.setName(jsonObject.getString("customerNickname"));
					}else{
						entity.setName(jsonObject.getString("remarksName"));
					}//relationType
					FriendHttpUtil.requestAttentionTofriends(DoctorAttentionMyListActivity.this, null, entity);					
				}
			});
			
			//未读消息
			//未读消息
			int size = appData.getNoReadMesgSize( jsonObject.getString("customerId"));
			if (size != 0) {
				holder.message.setVisibility(View.VISIBLE);
				String readCount=size >100 ? "99+":String.valueOf(size);
				holder.message.setText(readCount);
			} else {
				holder.message.setVisibility(View.GONE);
			}
			return convertView;
		}
			
	}
	
	private class viewHolder {
		private TextView note;//描述
		private ImageView head; // 头像
		private TextView personName; // 名称
		private ImageView headSex; // 性别
		private ImageView v;
		private TextView message;//消息的图标
		private ImageView attentionSalon;//是否是关注的好友
		private TextView distance;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		JSONObject jsonObject = mAdapter.getItem(position);
		CustomerInfoEntity entity=new CustomerInfoEntity();
		entity.setId(jsonObject.getString("customerId"));
		if("".equals(jsonObject.getString("remarksName"))){
			
			entity.setName(jsonObject.getString("customerNickname"));
		}else{
			entity.setName(jsonObject.getString("remarksName"));
		}
		FriendHttpUtil.onItemClick(this, entity);
	}
	@Override
	protected void onPause() {
		super.onPause();
		onQueryData();
	}
}
